package com.chinaums.open.api.internal.util.http;

import com.chinaums.open.api.OpenApiContext;
import com.chinaums.open.api.constants.ConfigBean;
import com.chinaums.open.api.internal.util.OpenApiLogger;
import com.chinaums.open.api.response.TokenResponse;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import static com.chinaums.open.api.internal.util.OpenBodySigUtil.generateSignature;

/**
 * Created with IntelliJ IDEA.
 * User: ZHANGWEI
 * Date: 2016/12/5
 * Time: 13:56
 * 所属模块：
 * 功能说明：http通用处理
 */
public class HttpTransport implements IHttpTransport {

    private static OkHttpClient okHttpClient;
    private static HttpTransport httpUtils;
    public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");

    private HttpTransport() {
    }

    public static synchronized HttpTransport getInstance() {
        if (httpUtils == null) {
            httpUtils = new HttpTransport();
            initialize();
        }
        return httpUtils;
    }

    private static void initialize() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * http post
     * @param isProd
     * @param url
     * @param token
     * @param requestString
     * @return
     */
    public String doPost(boolean isProd, String url, String token, String requestString) throws Exception {
        Request request = null;
        RequestBody requestBody = RequestBody.create(JSON,requestString);
        Response response;
        String responseInfo = "";
        if(!isProd){
            OpenApiLogger.logInfo("url:"+url);
            OpenApiLogger.logInfo("requst params:"+requestString);
        }
        if(StringUtils.isNotBlank(token)){
            request = new Request.Builder().url(url).addHeader("Authorization", "OPEN-ACCESS-TOKEN AccessToken=" + token).post(requestBody).build();
        }else{
            request = new Request.Builder().url(url).post(requestBody).build();
        }
        try {
            response = okHttpClient.newCall(request).execute();
            responseInfo = response.body().source().readUtf8();
            OpenApiLogger.logInfo("response :"+responseInfo);
            return responseInfo;
        } catch (Exception e) {
            OpenApiLogger.logError("通讯网络异常： "+e.getStackTrace());
            throw e;
        }
    }


    /**
     *  http post token方式
     * @param context
     * @param resquest_
     * @return
     * @throws Throwable
     */
    public String doPost(OpenApiContext context, String resquest_) throws Exception {
        String url = context.getApiServiceUrl();
        String appId=context.getAppId();
        ConfigBean configBean = context.getConfigBean();
        context.setRequest(resquest_);
        Request request = null;
        RequestBody requestBody = RequestBody.create(JSON,resquest_);
        Response response;
        String responseInfo = "";
        if(!configBean.isProd()){
            OpenApiLogger.logInfo("url:"+url);
            OpenApiLogger.logInfo("requst params:"+resquest_);

        }
        TokenResponse token = context.getCurrentToken();
        request = new Request.Builder().url(url).
                addHeader("Authorization","OPEN-ACCESS-TOKEN AccessToken=" + token.getAccessToken()+",AppId="+appId)
//                .addHeader("X-Access-Model","NEW")
                .post(requestBody).build();
        OpenApiLogger.logInfo("requst header:"+"OPEN-ACCESS-TOKEN AccessToken=" + token.getAccessToken()+",AppId="+appId);
        try {
            response = okHttpClient.newCall(request).execute();
            OpenApiLogger.logInfo("服务端返回code："+response.code()+" message:"+response.message());
            responseInfo = response.body().source().readUtf8();
            context.setResponse(responseInfo);
            OpenApiLogger.logInfo("response :"+responseInfo);
            return responseInfo;
        } catch (Exception e) {
            OpenApiLogger.logError("通讯网络异常： "+e.getStackTrace());
            throw e;
        }
    }


    /**
     *  http post signature方式
     * @param context
     * @param resquest_
     * @return
     * @throws Throwable
     */
    public String doPostSignature(OpenApiContext context, String resquest_) throws Exception {
        String url = context.getApiServiceUrl();
        ConfigBean configBean = context.getConfigBean();
        context.setRequest(resquest_);
        Request request = null;
        RequestBody requestBody = RequestBody.create(JSON,resquest_);
        Response response;
        String responseInfo = "";
        if(!configBean.isProd()){
            OpenApiLogger.logInfo("url:"+url);
            OpenApiLogger.logInfo("requst params:"+resquest_);

        }
        String authoriztion=generateSignature(context,resquest_,"POST");
        request = new Request.Builder().url(url).
                addHeader("Authorization",authoriztion)
                .post(requestBody).build();
        OpenApiLogger.logInfo("requst header:"+authoriztion);
        try {
            response = okHttpClient.newCall(request).execute();
            OpenApiLogger.logInfo("服务端返回code："+response.code()+" message:"+response.message());
            responseInfo = response.body().source().readUtf8();
            context.setResponse(responseInfo);
            OpenApiLogger.logInfo("response :"+responseInfo);
            return responseInfo;
        } catch (Exception e) {
            OpenApiLogger.logError("通讯网络异常： "+e.getStackTrace());
            throw e;
        }
    }

    public String doGet(OpenApiContext context, String request) {
        String url = context.getApiServiceUrl();
        String authoriztion=generateSignature(context,request,"GET");
        OpenApiLogger.logInfo("拼接的url :"+url+"?"+authoriztion);
        return url+"?"+authoriztion;
    }
}
